package com.yuezhu.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.yuezhu.R;
import com.yuezhu.been.DataChangedEvent;
import com.yuezhu.been.UserMsg;
import com.yuezhu.constante.BusAction;
import com.yuezhu.control.TaskEngine;
import com.yuezhu.global.ParallaxSwipeBackActivity;
import com.yuezhu.util.LogUtils;
import com.yuezhu.util.MyToast;
import com.yuezhu.util.NetworkUtils;
import com.yuezhu.util.StringUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class SignUpActivity extends ParallaxSwipeBackActivity implements View.OnFocusChangeListener, CompoundButton.OnCheckedChangeListener {
    @InjectView(R.id.bottom_left)
    View bottom_left;
    @InjectView(R.id.bottom_middle)
    View bottom_middle;
    @InjectView(R.id.bottom_right)
    View bottom_right;
    @InjectView(R.id.tv_agreement)
    TextView tvAgreement;
    @InjectView(R.id.et_signup_name)
    EditText etSignupName;
    @InjectView(R.id.et_signup_password)
    EditText etSignupPassword;
    @InjectView(R.id.et_signup_password_again)
    EditText etSignupPasswordAgain;
    @InjectView(R.id.et_signup_email)
    EditText etSignupEmail;
    @InjectView(R.id.cb_agreement)
    CheckBox cbAgreement;
//    @InjectView(R.id.cb_subscription_info)
//    CheckBox cbSubscriptionInfo;
    @InjectView(R.id.iv_bottome_left)
    ImageView ivBottomeLeft;
    @InjectView(R.id.iv_bottome_middle)
    ImageView ivBottomeMiddle;
    @InjectView(R.id.iv_bottome_right)
    ImageView ivBottomeRight;
    @InjectView(R.id.iv_menu)
    ImageView ivMenu;
    @InjectView(R.id.tv_title)
    TextView tvTitle;
    @InjectView(R.id.iv_quite)
    ImageView ivQuite;
    @InjectView(R.id.tv_version)
    TextView tvVersion;
    @InjectView(R.id.rl_version_up)
    LinearLayout rlVersionUp;
//    @InjectView(R.id.tv_subscibe)
//    TextView tvSubscibe;
    @InjectView(R.id.username_remind_text)
    TextView usernameRemindText;
    @InjectView(R.id.mail_remind_text)
    TextView mailRemindText;
    private String name;
    private String passWord;
    private String rePassWord;
    private String email;
    private boolean isAgreeMent = true;
//    private boolean isSubscribe = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        ButterKnife.inject(this);
        initView();
        setListeners();
    }


    @Override
    protected void initView() {
        ivMenu.setImageResource(R.drawable.zhuoyun);
        tvTitle.setText("用户注册");
        addClickableText();
//        cbSubscriptionInfo.setChecked(isSubscribe);
        cbAgreement.setChecked(isAgreeMent);
        setEditextHint();
        ivBottomeLeft.setImageResource(R.drawable.error);
        ivBottomeRight.setImageResource(R.drawable.right);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        ivQuite.setOnClickListener(this);
        etSignupName.addTextChangedListener(new NameWatcher());
        etSignupName.setOnFocusChangeListener(this);
        etSignupPassword.addTextChangedListener(new PasswordWatcher());
        etSignupPasswordAgain.addTextChangedListener(new RePasswordWatcher());
        etSignupPasswordAgain.setOnFocusChangeListener(this);
        etSignupEmail.addTextChangedListener(new EmailWatcher());
        etSignupEmail.setOnFocusChangeListener(this);
        cbAgreement.setOnCheckedChangeListener(this);
//        cbSubscriptionInfo.setOnCheckedChangeListener(this);
        ivBottomeLeft.setOnClickListener(this);
        ivBottomeRight.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_quite:
                EventBus.getDefault().post(new BusAction.quitApp());
//                BusProvider.getInstance().post(new DataChangedEvent(BusAction.QUIT_APP));
                finish();
                System.exit(0);
                break;
            case R.id.iv_bottome_left:
                finish();
                break;
            case R.id.iv_bottome_right:
                if (!isAgreeMent) {
                    MyToast.showDefaltToast("必须同意使用条款和隐私声明的内容才能够注册为卓云用");
                    return;
                }
                if (StringUtil.isEmpty(name)) {
                    MyToast.showDefaltToast("用户名不能为空");
                    return;
                } else if (name.length() < 5 || name.length() > 20) {
                    MyToast.showDefaltToast("无效的用户名，用户名必须为5至20位的英文字母或数字的组合（不区分大小写）");
                    return;
                }
                if (StringUtil.isEmpty(passWord)) {
                    MyToast.showDefaltToast("密码不能为空");
                    return;
                }
                if (StringUtil.isEmpty(email)) {
                    MyToast.showDefaltToast("邮件不能为空");
                    return;
                }
                if (NetworkUtils.isNetworkAvailable(getApplicationContext())) {
                    //访问网络注册
                    etSignupEmail.clearFocus();
                    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (usernameRemindText.getVisibility() == View.VISIBLE || mailRemindText.getVisibility() == View.VISIBLE) {
                                MyToast.showDefaltToast("注册失败，用户名或邮箱有重复，请修改后再次注册!");
                            } else {
                                TaskEngine.getInstance().startRegistTask(queue, name, passWord, email, ResponseLis, Errorlis);
                            }
                        }
                    }, 1000);
                } else {
                    MyToast.showDefaltToast("网络不可用");
                }
                break;
        }

    }

    // 注册成功
    Response.Listener ResponseLis = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject json) {
            LogUtils.e("注册成功" + "sec" + json.toString());
            try {
                String respCode = json.getString("respCode");
                if (StringUtil.equal(respCode, "OK")) {
                    MyToast.showDefaltToast("您已成功注册成为卓云用户,系统已向您注册的电子邮件地址发送了账\n" +
                            "户激活邮件,请点击邮件中的链接激活账户,并使用您注册时使用的用户名/电子邮件地址与密码登录应用");
                    UserMsg userMsg = UserMsg.getInstance();
                    userMsg.setUserID(json.getString("userID"));
                    userMsg.setUserName(json.getString("userName"));
                    EventBus.getDefault().post(new BusAction.signupSucceed());
//                    BusProvider.getInstance().post(new DataChangedEvent(BusAction.SIGNUP_SUCCEED));
                    finish();
                } else {
                    MyToast.showDefaltToast(json.getString("respDesc"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    };

    /**
     * 注册失败
     */
    Response.ErrorListener Errorlis = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            LogUtils.e("失败", "error  " + volleyError.toString());
        }
    };

    class NameWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            name = s.toString().trim();
        }
    }

    class PasswordWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            passWord = s.toString().trim();

        }
    }

    class RePasswordWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            rePassWord = s.toString().trim();
        }
    }

    class EmailWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            email = s.toString().trim();
        }
    }
    //edittext是否获取焦点

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        switch (v.getId()) {
            case R.id.et_signup_name:
                if (!hasFocus) {
                    if (!StringUtil.isEmpty(name)) {
                        if (name.length() < 5 || name.length() > 20) {
                            MyToast.showDefaltToast("无效的用户名，用户名必须为5至20位的英文字母或数字的组合（不区分大小写）");
                        } else {
                            //联网检测用户名是否有效
                            TaskEngine.getInstance().startCkeckUserNameTask(queue, name, new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject json) {
                                    try {
                                        String respCode = json.getString("respCode");
                                        if (!StringUtil.equal(respCode, "OK")) {
                                            MyToast.showDefaltToast("获取数据失败");
                                        } else {
                                            if (json.getInt("respNo") == 200) {
                                                usernameRemindText.setVisibility(View.INVISIBLE);
                                            } else {
                                                usernameRemindText.setVisibility(View.VISIBLE);
                                            }
                                        }
                                    } catch (Exception e) {
                                    }
                                }
                            }, new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError volleyError) {

                                }
                            });
                        }
                    } else {
                        MyToast.showDefaltToast("用户名不能为空");
                    }
                }
                break;
            case R.id.et_signup_password_again:
                if (!hasFocus && !StringUtil.isEmpty(rePassWord)) {
                    if (!StringUtil.equal(rePassWord, passWord)) {
                        LogUtils.e("两次输入密码不同");
                        MyToast.showDefaltToast("两次输入密码不同");
                    }
                }
                break;
            case R.id.et_signup_email:
                if (!hasFocus) {
                    if (StringUtil.isEmpty(email)) {
                        MyToast.showDefaltToast("邮件不能为空");
                    } else if (!StringUtil.isEmail(email)) {
                        MyToast.showDefaltToast("邮件格式不正确");
                    } else {
                        TaskEngine.getInstance().startCkeckUserMailTask(queue, email, new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject json) {
                                try {
                                    String respCode = json.getString("respCode");
                                    if (!StringUtil.equal(respCode, "OK")) {
                                        MyToast.showDefaltToast("获取数据失败");
                                    } else {
                                        if (json.getInt("respNo") == 200) {
                                            mailRemindText.setVisibility(View.INVISIBLE);
                                        } else {
                                            mailRemindText.setVisibility(View.VISIBLE);
                                        }
                                    }
                                } catch (Exception e) {
                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError volleyError) {

                            }
                        });
                    }
                }
                break;
        }
    }

    //checkbox监听
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_agreement:
                isAgreeMent = isChecked;
                LogUtils.e("isAgreeMent" + isChecked);
                break;
//            case R.id.cb_subscription_info:
//                isSubscribe = isChecked;
//                LogUtils.e("isSubscribe" + isChecked);
//                break;
        }
    }

    //edittext的hint设置
    private void setEditextHint() {
        //图片
        String name = "用户名*";
        SpannableString spanString1 = new SpannableString(name);
        spanIcon(spanString1, name);
        etSignupName.setHint(spanString1);

        String password = "登录密码*";
        SpannableString spanString2 = new SpannableString(password);
        spanIcon(spanString2, password);
        etSignupPassword.setHint(spanString2);

        String repassword = "重复密码*";
        SpannableString spanString3 = new SpannableString(repassword);
        spanIcon(spanString3, repassword);
        etSignupPasswordAgain.setHint(spanString3);
        //字体大小
        String text1 = "电子邮箱地址";
        String text2 = "（用于激活账户，请确保其真实有效）*";
        String email = text1 + text2;
        SpannableString spanString4 = new SpannableString(email);
        AbsoluteSizeSpan span = new AbsoluteSizeSpan(10, true);
        spanString4.setSpan(span, text1.length(), email.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanIcon(spanString4, email);
        etSignupEmail.setHint(spanString4);
    }

    //hint图片设置
    private void spanIcon(SpannableString spanString, String text) {
        ForegroundColorSpan spanname = new ForegroundColorSpan(Color.RED);
        spanString.setSpan(spanname, text.length() - 1, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }


    //已阅读并同意本应用的使用条款和隐私声明
    protected void addClickableText() {

        String text1 = "已阅读并同意本应用的";
        String text2 = "使用条款";
        String text3 = "和";
        String text4 = "隐私声明";
        String text = text1 + text2 + text3 + text4;
        SpannableString spannableString = new SpannableString(text);
        ClickableSpan clickableSpan = new ClickableSpan() {

            @Override
            public void onClick(View widget) {
                avoidHintColor(widget);
                Intent intent = new Intent(SignUpActivity.this, WebActivity.class);
                intent.putExtra("weburl", "http://www.zcloud-online.com/AppService/TermsOfUse.html");
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.actionbarbg));
                ds.setUnderlineText(true);
                ds.clearShadowLayer();
            }

        };
        ClickableSpan clickableSpan2 = new ClickableSpan() {

            @Override
            public void onClick(View widget) {
                avoidHintColor(widget);
                Intent intent = new Intent(SignUpActivity.this, WebActivity.class);
                intent.putExtra("weburl", "http://www.zcloud-online.com/AppService/UserPrivacyStatements.html");
                startActivity(intent);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.actionbarbg));
                ds.setUnderlineText(true);
                ds.clearShadowLayer();
            }

        };
        int start = text1.length();
        int end = (text2 + text1).length();
        spannableString.setSpan(clickableSpan, start, end,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        int start2 = text1.length() + text2.length() + text3.length();
        int end2 = text.length();
        spannableString.setSpan(clickableSpan2, start2, end2,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvAgreement.setText(spannableString);
        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
    }

    //设置点击文字的背景颜色
    private void avoidHintColor(View view) {
        if (view instanceof TextView)
            ((TextView) view).setHighlightColor(getResources().getColor(android.R.color.transparent));
    }


}
